package com.binhthuan.catechist.server.util;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class JsonConverter {
    private static class SqlTimestapConverter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {
        static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

        @Override
        public JsonElement serialize(Timestamp src, Type srcType, JsonSerializationContext arg2) {
            return new JsonPrimitive(sdf.format(src));
        }

        @Override
        public Timestamp deserialize(JsonElement json, Type srcType, JsonDeserializationContext arg2)
                throws JsonParseException {
            Timestamp result = null;
            try {
                result =  new Timestamp(sdf.parse(json.getAsString()).getTime());
            } catch (ParseException e) {
                e.printStackTrace();
                result = new Timestamp(new Date().getTime());
            }
            
            return result;
        }
    }

    private static JsonConverter converter;
    private static Gson gson;

    private JsonConverter() {
        gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new SqlTimestapConverter()).setDateFormat("yyyy-MM-dd'T'HH:mm:ss").excludeFieldsWithoutExposeAnnotation().create();
    }

    public static JsonConverter getInstance() {
        if (converter == null) {
            converter = new JsonConverter();
        }

        return converter;
    }

    public String toJson(Object obj) {
        return gson.toJson(obj);
    }
    
    public Object fromJson(String json, Class<?> classOfT) {
        return gson.fromJson(json, classOfT);
    }
}
